﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ShareMarking.Systems.Service;
using System.Configuration;
using ZXing;
using ZXing.QrCode;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using ZXing.QrCode.Internal;
using ZXing.Common;
using ShareMarking.Interface;
using System.Net;
using System.Text.RegularExpressions;
using ShareMarking.Entity;
using ShareMarking.Service;

namespace ShareMarking.Web.admin.EnterPrise.Activity
{
    public partial class Action2 :ManagePage
    {
        #region 属性=====================================
        private static string httpstr = ConfigurationManager.AppSettings["vigohttp"];
        private static string signsecret = ConfigurationManager.AppSettings["signscrect"];
        private static string diyhttp2 = ConfigurationManager.AppSettings["diyhttp2"];//本系统网站域名使用第二个域名 
        //private static string diyapi = ConfigurationManager.AppSettings["diyapi"];//跳转网站域名 
        protected String Par_Diy_Name 
        {
            get { return txt_Diy_Name.Text; }
            set { txt_Diy_Name.Text = value; }
        }
        protected String Par_Diy_Url
        {
            get { return txt_Diy_Url.Text; }
            set { txt_Diy_Url.Text = value; }
        }
        //
        protected String Par_Diy_Desc
        {
            get { return txt_Diy_Desc.Text; }
            set { txt_Diy_Desc.Text = value; }
        }

        protected String Par_Diy_Manager
        {
            get { return txt_Diy_Manager.Text; }
            set { txt_Diy_Manager.Text = value; }
        }
        protected DateTime ParStartTime_diy
        {
            get { return txtStartTime_diy.Text.ConvertTo<DateTime>(); }
            set { txtStartTime_diy.Text = value.ToString("yyyy-MM-dd HH:mm:ss"); }
        }

        protected DateTime ParEndTime_diy
        {
            get { return txtEndTime_diy.Text.ConvertTo<DateTime>(); }
            set { txtEndTime_diy.Text = value.ToString("yyyy-MM-dd HH:mm:ss"); }
        }
        protected String Par_Diy_wxTitle
        {
            get { return txt_Diy_wxTitle.Text; }
            set { txt_Diy_wxTitle.Text = value; }
        }
        protected String Par_Diy_wxDesc
        {
            get { return txt_Diy_wxDesc.Text; }
            set { txt_Diy_wxDesc.Text = value; }
        }

        protected String Par_Diy_wxbeforeUrl
        {
            get { return txt_Diy_beforeurl.Text; }
            set { txt_Diy_beforeurl.Text = value; }
        }

        protected String Par_Diy_wxafterUrl
        {
            get { return txt_Diy_afterurl.Text; }
            set { txt_Diy_afterurl.Text = value; }
        }

        protected String parsacode 
        {
            get { return txtsacode.Text; }
            set { txtsacode.Text = value; }
        }
         protected String  txt_Url
        {
            get { return txtUrl.Text; }
            set { txtUrl.Text = value; }
        }

        #endregion

        #region 初始化===================================

        protected string action = DTEnums.ActionEnum.Add.ToString(); //操作类型
        private int id = 0;
        private int rep = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            string _action = DTRequest.GetQueryString("action");
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                this.action = DTEnums.ActionEnum.Edit.ToString();//修改类型
                this.id = DTRequest.GetQueryInt("id");
                if (this.id == 0)
                {
                    JscriptMsg("传输参数不正确！", "back", "Error");
                    return;
                }
                if (!qr_ActivityService.Instance.Get_IsExist_ByWhere(qr_Activity._.ActivityID == this.id))
                {
                    JscriptMsg("信息不存在或已被删除！", "back", "Error");
                    return;
                }
            }
            if (!Page.IsPostBack)
            {
                //ChkAdminLevel("user_list", ShareMarkingEnums.ActionEnum.View.ToString()); //检查权限

                //绑定下拉框

                if (action == DTEnums.ActionEnum.Edit.ToString()) //修改
                {
                    ShowInfo(this.id);
                }
            }
        }

        #endregion

        #region 绑定下拉框===============================

        protected void ddl_IsSenate_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (ddl_IsSenate.SelectedValue == "true")            
            //{

            //}
        }
        #endregion

        #region 赋值操作=================================
        private void ShowInfo(int _id)
        {
            //Par_Diy_Name Par_Diy_Url Par_Diy_Desc Par_Diy_Manager ParStartTime_diy ParEndTime_diy Par_Diy_wxTitle Par_Diy_wxDesc
            var entity = qr_ActivityService.Instance.Get_SingleEntity_byWhere(qr_Activity._.ActivityID == _id);
            if (entity == null) return;
            Par_Diy_Name = entity.A_Name;
            Par_Diy_Desc = entity.A_Desc;
            Par_Diy_Manager = entity.A_Manager;
            Par_Diy_wxTitle = entity.A_wxTitle;
            Par_Diy_wxDesc = entity.A_wxDesc;
            Par_Diy_Url = entity.A_wxUrl;
            Par_Diy_wxbeforeUrl = entity.A_wxbeforeUrl;
            Par_Diy_wxafterUrl = entity.A_wxafterUrl;
            parsacode = entity.A_SaCode;//
            ParStartTime_diy = entity.A_StartTime.ConvertTo<DateTime>();
            ParEndTime_diy = entity.A_EndTime.ConvertTo<DateTime>();
        }
        #endregion

        #region 增加操作=================================
        private bool DoAdd()
        {
            var cliUrl = ConfigurationManager.AppSettings["cliUrl"];
            var mhid = ConfigurationManager.AppSettings["mhid"];
            string diystr = "";
            var result = false;
            try
            {
                #region 添加活动无参二维码

                #region 根据时间判断路径
                var currenturl = "";
                if (DateTime.Now < ParStartTime_diy)
                {
                    currenturl = Regex.Replace(Par_Diy_wxbeforeUrl.ToString().Trim(), @"\s", "");//去掉链接URL的空字符串//Par_Diy_wxbeforeUrl;
                }
                else if (DateTime.Now > ParStartTime_diy && DateTime.Now < ParEndTime_diy)
                {
                    currenturl = Regex.Replace(Par_Diy_Url.ToString().Trim(), @"\s", "");//去掉链接URL的空字符串
                }
                else
                {
                    currenturl = Regex.Replace(Par_Diy_wxafterUrl.ToString().Trim(), @"\s", "");//去掉链接URL的空字符串//Par_Diy_wxafterUrl;
                }
                //var ssacode = "";
                //if (currenturl.Contains("?"))
                //{
                //    ssacode = "$sacode=" + Regex.Replace(parsacode.ToString().Trim(), @"\s", "");
                //}
                //else
                //{
                //    ssacode = "?sacode=" + Regex.Replace(parsacode.ToString().Trim(), @"\s", "");
                //}
                #endregion

                #region 获取Sceneid
                var sceneid = 0;
                qr_QrCodeType type = qr_QrCodeTypeService.Instance.Get_SingleEntity_byWhere(qr_QrCodeType._.QrCodeTypeID == 1003);
                if (type.QT_CurrentIndex.ConvertTo<int>() == 1)
                {
                    sceneid = type.QT_CurrentIndex.ConvertTo<int>();
                }
                else
                {
                    sceneid = type.QT_CurrentIndex.ConvertTo<int>() + 1;
                }               
                #endregion

                #region 生成二维码方法
                
                //string url = GenerateQrCodeImg(diystr);
                //string url = Generate3(oneurl);
                //String cliUrl = "https://cli.im/api/qrcode/code?text=//cli.im&mhid=sELPDFnok80gPHovKdI";
                //requestUrl = requestUrl.Replace("text", accessToken);
                //var resultentity = vigo.GenerateQrCodeImg(diystr);
                //string[] sArray = resultentity.Split('/');
                //string system = sArray[0]; //context.Request["system"] request.Browser.Platform;this.GetOSNameByUserAgent(userAgent);//操作系统
                //string client = sArray[1];//浏览器名称request.Browser.Browser

                diystr = diyhttp2 + "/a.aspx?c=" + sceneid.ToString();//（网站域名+访问页面+场景ID）
                var vigo = new ShareMarking.Interface.Qrcode_diy(diystr);
                
                resultdiy resultdiy = new resultdiy();
               var resultentity= ComLib.JsonHelper.JsonDeserialize<resultdiy>(vigo.GenerateQrCodeImg(diystr));
                
                #endregion

                #region 循环判断返回错误就重新请求

                while (resultentity.subcode == "01")
                {
                    ComLib.LogLib.Log4NetBase.Log("错误信息:" + resultentity.msg + "/sceneid=" + sceneid);
                    sceneid += 1;
                    diystr = diyhttp2 + "/a.aspx?c=" + sceneid.ToString();
                    resultentity= ComLib.JsonHelper.JsonDeserialize<resultdiy>(vigo.GenerateQrCodeImg(diystr));
                }

                #endregion

                #region 保存二维码到数据库

                if (resultentity.subcode == "00")
                {
                    #region 保存二维码到数据库
                    qr_DiyCode qrdiycode = new qr_DiyCode()
                    {
                        scene_id = sceneid.ToString(),
                        type = 1003,
                        code_url = diystr,//唯一短码
                        source_url = currenturl,//(currenturl + ssacode).Replace('&', '$'),//跳转的真实url
                        qrcode_url = diyhttp2 + resultentity.result,//二维码图片保存路径(网站域名+图片目录)
                        isdelete = false,
                        CreateOn = DateTime.Now,
                    };
                    qr_DiyCodeService.Instance.Add_Entity(qrdiycode);
                    #endregion

                    #region 保存活动
                    var entity = new qr_Activity();
                    entity.A_Name = Regex.Replace(Par_Diy_Name.ToString().Trim(), @"\s", "");
                    entity.A_Desc = Par_Diy_Desc;
                    entity.A_Manager = Par_Diy_Manager;
                    entity.A_wxQrCodeID = qrdiycode.id.ToString();
                    entity.A_wxSceneID = qrdiycode.scene_id.ToString();
                    entity.A_wxTitle = Par_Diy_wxTitle;
                    //entity.A_wxImgUrl = Par_A_wxImgUrl;//
                    entity.A_wxDesc = Par_Diy_wxDesc;
                    entity.A_wxUrl = Par_Diy_Url;
                    entity.A_wxbeforeUrl = Par_Diy_wxbeforeUrl;
                    entity.A_wxafterUrl = Par_Diy_wxafterUrl;
                    entity.A_SaCode = parsacode;
                    entity.A_StartTime = ParStartTime_diy;
                    entity.A_EndTime = ParEndTime_diy;
                    entity.CreateOn = DateTime.Now;//
                    entity.isneedupdate = false;//
                    entity.A_currentUrl = currenturl;//当前时间的currurl
                    entity.isSenate = 0;//无参标识//
                    var qr_act = qr_ActivityService.Instance.Add_Entity(entity);
                    #endregion

                    #region 添加关联
                    qr_QrCodeRelate qrrelate = new qr_QrCodeRelate()
                    {
                        qr_Type = 1003,//1003是无参活动类型
                        qr_CodeID = qrdiycode.id,//无参二维码id
                        qr_Scene_ID = qrdiycode.scene_id,//场景值
                        rel_Code = entity.ActivityID.ToString(),//无参活动ID
                        IsDelete = false,
                        CreateOn = DateTime.Now
                    };
                    var qrre = qr_QrCodeRelateService.Instance.Add_Entity(qrrelate);
                    #endregion

                    #region 更改二维码类型表
                    type.QT_CurrentIndex = sceneid;//已使用的场景id
                    type.QT_Used = type.QT_Used + 1;//已使用+1
                    type.QT_Surplus = type.QT_Surplus - 1;//未使用-1
                    type.ModifiedOn = DateTime.Now;
                    result = qr_QrCodeTypeService.Instance.Update_Entity(type);
                    #endregion
                }    
  
                #endregion

                #endregion

                if (result)
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加qr_Activity"); //记录日志
                }
            }
            catch (Exception ex)
            {
                ComLib.LogLib.Log4NetBase.Log("新增无参活动错误::::" + ex.Message + ex.StackTrace);
            }
            return result;
        }
        #endregion        

        #region 修改操作=================================
        private bool DoEdit(int _id)
        {
            var entity = qr_ActivityService.Instance.Get_SingleEntity_byWhere(qr_Activity._.ActivityID == _id);
            if (entity == null) return false;
            var httpstr = ConfigurationManager.AppSettings["vigohttp"];
            var signsecret = ConfigurationManager.AppSettings["signscrect"];
            var result = false;
            try
            {
                #region 修改活动二维码             
                if (!entity.A_wxQrCodeID.IsNullOrEmpty())
                {
                    #region 根据时间判断路径
                    var currenturl = "";
                    if (DateTime.Now < ParStartTime_diy)
                    {
                        currenturl = Regex.Replace(Par_Diy_wxbeforeUrl.ToString().Trim(), @"\s", "");//去掉链接URL的空字符串//Par_Diy_wxbeforeUrl;
                    }
                    else if (DateTime.Now > ParStartTime_diy && DateTime.Now < ParEndTime_diy)
                    {
                        currenturl = Regex.Replace(Par_Diy_Url.ToString().Trim(), @"\s", "");//去掉链接URL的空字符串
                    }
                    else
                    {
                        currenturl = Regex.Replace(Par_Diy_wxafterUrl.ToString().Trim(), @"\s", "");//去掉链接URL的空字符串//Par_Diy_wxafterUrl;
                    }
                    //var ssacode = "";
                    //if (currenturl.Contains("?"))
                    //{
                    //    ssacode = "$sacode=" + Regex.Replace(parsacode.ToString().Trim(), @"\s", "");
                    //}
                    //else
                    //{
                    //    ssacode = "?sacode=" + Regex.Replace(parsacode.ToString().Trim(), @"\s", "");
                    //}
                    #endregion

                    #region 修改二维码
                    var qr_diy = qr_DiyCodeService.Instance.Get_IsExist_ByWhere(qr_DiyCode._.id==entity.A_wxQrCodeID);
                    if (qr_diy)
                    {
                        #region 修改二维码路径
                        var qr_diyentity = qr_DiyCodeService.Instance.Get_SingleEntity_byWhere(qr_DiyCode._.id == entity.A_wxQrCodeID);
                        qr_diyentity.source_url = currenturl;//(currenturl + ssacode).Replace('&', '$');//Par_Diy_Url;//跳转的真实url
                        qr_diyentity.DateModified = DateTime.Now;
                        qr_DiyCodeService.Instance.Update_Entity(qr_diyentity);
                        #endregion

                        #region 修改活动
                        entity.A_Name = Regex.Replace(Par_Diy_Name.ToString().Trim(), @"\s", "");
                        entity.A_Desc = Par_Diy_Desc;//Par_A_Desc;
                        entity.A_Manager = Par_Diy_Manager;
                        entity.A_wxQrCodeID = qr_diyentity.id.ToString();
                        entity.A_wxSceneID = qr_diyentity.scene_id.ToString();
                        entity.A_wxTitle = Par_Diy_wxTitle;
                        entity.A_wxDesc = Par_Diy_wxDesc;
                        entity.A_wxUrl = Par_Diy_Url;
                        entity.A_wxbeforeUrl = Par_Diy_wxbeforeUrl;
                        entity.A_wxafterUrl = Par_Diy_wxafterUrl;
                        entity.A_StartTime = ParStartTime_diy;
                        entity.A_EndTime = ParEndTime_diy;
                        entity.DateModified = DateTime.Now;
                        //entity.isneedupdate = false;
                        entity.A_currentUrl = currenturl;//当前时间的currurl
                        result = qr_ActivityService.Instance.Update_Entity(entity);
                        #endregion
                    }
                    else
                    {
                        ComLib.LogLib.Log4NetBase.Log("修改无参活动二维码失败！记录不存在，id=" + entity.A_wxQrCodeID);
                    }
                    #endregion
                }                              
                #endregion
                if (result)
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改qr_Activity:" + entity.ActivityID); //记录日志
                }
            }
            catch (Exception ex)
            {
                ComLib.LogLib.Log4NetBase.Log("修改活动二维码错误::::" + ex.Message + ex.StackTrace);
            }
            return result;
        }
        #endregion

        #region 保存按钮事件=============================

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (action == DTEnums.ActionEnum.Edit.ToString())
            { 
                DoEdit(this.id);
                JscriptMsg("修改成功！", "List.aspx?isSenate=false", "Success");
            }
            else //添加
            {
                if (!DoAdd())
                {
                    JscriptMsg("保存过程中发生错误！", "", "Error");
                    return;
                }
                JscriptMsg("添加成功！", "List.aspx?isSenate=false", "Success");
            }
        }

        #endregion

        #region  测试辅助类===============================
        //测试生成码
        protected void test_Click(object sender, EventArgs e)
        {
            var short_httpstr = ConfigurationManager.AppSettings["short_httpstr"];
            var short_appkey = ConfigurationManager.AppSettings["short_appkey"];
            var short_signsecret = ConfigurationManager.AppSettings["short_signsecret"];

            var cliUrl = ConfigurationManager.AppSettings["cliUrl"];
            var mhid = ConfigurationManager.AppSettings["mhid"];

            string oneurl = "";
            string scenestr = "";
            string posthttp = "";
            string diystr = "";
            string Random = "";

            var sceneid = 0;
            //qr_QrCodeType type = qr_QrCodeTypeService.Instance.Get_SingleEntity_byWhere(qr_QrCodeType._.QrCodeTypeID == 1003);
            //sceneid = type.QT_CurrentIndex.ConvertTo<int>() + 1;

            try
            {

                if (txt_Diy_Url.Text.Trim().IsNullOrEmpty())
                {
                    JscriptMsg("请输入二维码路径！", "", "Error");
                }
                else
                {
                    var qrcodecontent = Regex.Replace(txt_Diy_Url.ToString(), @"\s+", " ").Trim();
                    //CheckQrcode check = new CheckQrcode();
                    //var qrcodecontent = check.Read1Decode(txt_Diy_Url.Text.Trim());
                    Label2.Text = qrcodecontent;
                }
                #region 短码接口申请
                //var vigo = new ShareMarking.Interface.Qrcode_diy(cliUrl, mhid);
                //http://admin.mjn.c2d.me/a.aspx?c=100001            
                diystr = diyhttp2 + "/a.aspx?c=" + sceneid.ToString();
                //string url = Generate3(diystr);
                // Label1.Text = url;
                ////Random = GenerateCheckCodeNum(5);//生成5位不重复的字符
                ////diystr = scenestr + Random;//自定义参数sceneid+随机5位数
                //var resultentity = vigo.CreateQrCode(diystr);

                //string imgurl = " //qr.api.cli.im/qr?data=http%3A%2F%2Fadmin.mjn.c2d.me%2Fq%2F%3Fc%3D100001&level=H&transparent=false&bgcolor=%23FFFFFF&forecolor=&blockpixel=12&marginblock=2&logourl=%2F%2Foss-cn-hangzhou.aliyuncs.com%2Fpublic-cli%2Ffree%2Fd447faf66c981678d7b59672cbae85271471397734.jpg&size=400&text=&logoshape=no&fontsize=30&fontfamily=msyh.ttf&fontcolor=%23000000&incolor=&outcolor=&background=&qrcode_eyes=&wper=0&hper=0&lper=0&tper=0&eye_use_fore=1&qrpad=10&kid=cliim&key=8a449e893f5d8473ef492776e7e8e32b";
                //SaveQrCode(imgurl);

                #endregion
                #region 自增sceneid重新请求直到成功为止
                //while (resultentity.msg == "fixed参数有误")
                //{
                //    ComLib.LogLib.Log4NetBase.Log("错误信息:" + resultentity.msg + "/sceneid=" + sceneid);
                //    sceneid += 1;
                //    //scenestr = sceneid.ToString();
                //    //Random = GenerateCheckCodeNum(5);//生成5位不重复的字符
                //    //diystr = scenestr + Random;//自定义参数sceneid+随机5位数
                //    resultentity = vigo.CreateShortUrl(oneurl, sceneid.ToString());
                //}
                #endregion
                // "success":"1",
                //"result":{"short_url":"http://k3v.cn/100001","keyid":"100001","source_url":"https://www.taobao.com/market/3c/shouji.php?spm=a21bo.50862.201867-main.13.QJOgln","exits":"0"}}

                //D:\C#Work\桂林交接项目\7-26美赞臣测试\美赞臣二维码-正式版\Web\ShareMarking.Web\upload\20160816\2228310218.png&http://k3v.cn/100001
                //if (resultentity.success == "1")
                //{
                //    oneurl = resultentity.result.short_url;
                //    posthttp = resultentity.result.source_url;
                //    string url = Generate3(oneurl);//创建本地二维码
                //    Label1.Text = url;
                //}
                //else if (resultentity.msg == "url已存在")
                //{

                //}

            }
            catch (Exception ex)
            {
                ComLib.LogLib.Log4NetBase.Log("3、====新增短码失败========请求的URL:" + posthttp + "::==返回URL:" + oneurl + "====" + ex.StackTrace);
            }
        }
        //解二维码
        protected void Decode_Click(object sender, EventArgs e)
        {
            if (txt_Url.IsNullOrEmpty())
            {
                JscriptMsg("请输入二维码路径！", "", "Error");
            }
            else
            {
                //CheckQrcode check = new CheckQrcode();
                //var qrcodecontent = check.Read1Decode(txt_Diy_Url.Text.Trim());
                string str = txt_Url.ToString();
                string qr2 = System.Text.RegularExpressions.Regex.Replace(txt_Url.ToString().Trim(), @"\s", "");
                string qr1 = txt_Url.ToString().Trim(); //Regex.Replace(txt_Url, @"\s+", " ").Trim();
                Label2.Text = qr1 + "//" + qr2;
            }
        }
        #endregion

        #region  自定义辅助类=============================
        /// <summary>   
        /// 取得HTML中所有图片的 URL。   
        /// </summary>   
        /// <param name="sHtmlText">HTML代码</param>   
        /// <returns>图片的URL列表</returns>   
        public static string[] GetHtmlImageUrlList(string sHtmlText)
        {
            // 定义正则表达式用来匹配 img 标签   
            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);

            // 搜索匹配的字符串   
            MatchCollection matches = regImg.Matches(sHtmlText);
            int i = 0;
            string[] sUrlList = new string[matches.Count];

            // 取得匹配项列表   
            foreach (Match match in matches)
                sUrlList[i++] = match.Groups["imgUrl"].Value;
            return sUrlList;
        }
        /// <summary>
        /// 生成二维码,保存成图片
        /// </summary>
        public static void Generate1(string text)
        {
            CreateDir();
            BarcodeWriter writer = new BarcodeWriter();
            writer.Format = BarcodeFormat.QR_CODE;
            QrCodeEncodingOptions options = new QrCodeEncodingOptions();
            options.DisableECI = true;
            //设置内容编码
            options.CharacterSet = "UTF-8";
            //设置二维码的宽度和高度
            options.Width = 500;
            options.Height = 500;
            //设置二维码的边距,单位不是固定像素
            options.Margin = 1;
            writer.Options = options;

            Bitmap map = writer.Write(text);
            string filename = @"H:\桌面\截图\generate1.png";
            //http://wx.meadjohnson.com.cn/API/Uploads/ercode/20160219/145584459968212.png
            map.Save(filename, ImageFormat.Png);
            map.Dispose();

        }

        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        public static string BuildQuery(IDictionary<string, string> parameters)
        {
            StringBuilder postData = new StringBuilder();

            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名为空的参数
                if (!string.IsNullOrEmpty(name))
                {
                    postData.Append(name);
                    if (name == "url")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                    }
                    else
                    {
                        postData.Append(value);
                    }
                }
            }
            return postData.ToString();
        }

        public static void CreateDir()
        {
            DateTime now = DateTime.Now;
            string year = now.ToString("yyyyMMdd"); //+ sExt;
            string avatarDir = string.Format(@"~/API/Uploads/ercode/{0}", year);
            //string avatarDir = string.Format("/Upload/avatar/{0}/",uid);
            if (!Directory.Exists(HttpContext.Current.Server.MapPath(avatarDir)))
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(avatarDir));
        }  
     
        #region GetRandom
        private string GetRandom(int length)
        {
            byte[] random = new Byte[length / 2];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetNonZeroBytes(random);

            StringBuilder sb = new StringBuilder(length);
            int i;
            for (i = 0; i < random.Length; i++)
            {
                sb.Append(String.Format("{0:X2}", random[i]));
            }
            return sb.ToString();
        }
        /// <summary>
        /// 生成随机字符串（数字+字符）
        /// </summary>
        /// <param name="codeCount"></param>
        /// <returns></returns>
        public string GenerateCheckCode(int codeCount)
        {
            string str = string.Empty;
            long num2 = DateTime.Now.Ticks + this.rep;
            this.rep++;
            Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> this.rep)));
            for (int i = 0; i < codeCount; i++)
            {
                char ch;
                int num = random.Next();
                if ((num % 2) == 0)
                {
                    ch = (char)(0x30 + ((ushort)(num % 10)));
                }
                else
                {
                    ch = (char)(0x41 + ((ushort)(num % 0x1a)));
                }
                str = str + ch.ToString();
            }
            return str;
        }

        /// <summary>
        /// 生成随机不重复的字符
        /// </summary>
        /// <param name="codeCount"></param>
        /// <returns></returns>
        public string GenerateCheckCodeNum(int codeCount)
        {
            string str = string.Empty;
            long num2 = DateTime.Now.Ticks + this.rep;
            this.rep++;
            Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> this.rep)));
            for (int i = 0; i < codeCount; i++)
            {
                int num = random.Next();
                str = str + ((char)(0x30 + ((ushort)(num % 10)))).ToString();
            }
            return str;
        }
        #endregion
   #endregion
    }
}